<?php
/**
 * PHP Framework Seo Google Image class
 *
 * @author Andrew <andrew@vitche.com>
 * @author Frozen Rain <frozenrain@mail.ru>
 **/
class GoogleImage extends SearchReference {

    private $Image = null;

    public function __construct($query) {

        parent::__construct();

        $localPath = "";
        $Cache = Cache::load();
        $cacheKey = "GoogleImage.content_uri=" . $query;
        if ($Cache->exists($cacheKey)) {

            Trace::writeLine("GoogleImage::__construct from cache");

            $Image = new Image();
            $Image->content_uri = $Cache->get($cacheKey);
            $this->Image = $Image;
        } else {

            Trace::writeLine("GoogleImage::__construct from SearchReference");

            $images = array();

            // Get image from the Google search service
            try {
                $images = $this->findImages($query);
            } catch (SoapFault $excp) {
                Trace::writeLine("GoogleImage::__construct SoapFault");
            }

            if (is_array($images) && count($images)) {
                $this->Image = array_pop($images);
            }

            // Whether an image was found
            if (isset($this->Image)) {
                $uri = $this->Image->content_uri;
                $dotPosition = (int)strrpos($uri, ".") + 1;
                $extensionLength = strlen($uri) - $dotPosition;
                $extension = substr($uri, $dotPosition, $extensionLength);

                // TODO: Move to settings
                global $root;
                $localPath = "$root/cache/$extension/$query.$extension";
                ob_start();
                file_put_contents($localPath, file_get_contents($uri));
                ob_end_clean();
                if (!is_file($localPath)) {
                    $this->Image->content_uri = "";
                }

                $this->Image->content_uri = $localPath;
            }

            // Cache any result including situations when nothing was found.
            // This is done to avoid making redundant search requests.
            $Cache->set($cacheKey, $localPath);
            $Cache->save();
        }
    }

    public function __get($name) {
        if (isset($this->Image)) {
            return $this->Image->$name;
        }

        return null;
    }
}
?>